/*
 * @Author: yangrongxin
 * @Date: 2021-05-31 17:08:57
 * @LastEditors: guoju
 * @LastEditTime: 2022-01-07 11:24:48
 */
import React, { useState, useEffect } from 'react';
import { View, Text } from '@tarojs/components';
import { cloneDeep } from 'lodash';
import styles from './index.module.less';

interface ICheckBoxGroupProps {
  checked?: boolean;
  label?: string;
  options: any[];
  value: any[];
  onChange: any; // 修改参数的onChange方法
  wapperClassName?: string; // 扩展样式名称
  itemClassName?: string; // 扩展子元素样式
  itemCheckClassName?: string; // 选中时的样式
}

const CheckBoxItem = (props: any) => {
  const { label, checked = true, onChange, itemClassName, itemCheckClassName } = props;

  return (
    <View
      className={`${styles.item} ${itemClassName} ${
        checked && itemCheckClassName ? itemCheckClassName : checked ? styles.itemCheck : ''
      }`}
      onClick={() => {
        onChange && onChange(!checked);
      }}
    >
      <View>
        <View className={checked ? styles.checked : ''}></View>
      </View>
      <Text>{label}</Text>
    </View>
  );
};

const CheckBoxGroup = (props: ICheckBoxGroupProps) => {
  const { options, value, onChange, wapperClassName, itemClassName, itemCheckClassName } = props;

  const [checkBoxValue, setCheckBoxValue] = useState(value);

  useEffect(() => {
    setCheckBoxValue([...value]);
  }, [value]);

  return (
    <View className={wapperClassName}>
      {options.map((item: any) => {
        return (
          <CheckBoxItem
            key={Math.random()}
            label={item.label}
            checked={checkBoxValue.indexOf(item.value) !== -1}
            onChange={(checked: boolean) => {
              if (checked) {
                checkBoxValue.push(item.value);
              } else {
                const itemIndex: number = checkBoxValue.indexOf(item.value);
                if (itemIndex !== -1) checkBoxValue.splice(itemIndex, 1);
              }
              setCheckBoxValue(cloneDeep(checkBoxValue));
              onChange(checkBoxValue);
            }}
            itemClassName={itemClassName}
            itemCheckClassName={itemCheckClassName}
          />
        );
      })}
    </View>
  );
};

export default CheckBoxGroup;
